package com.lz.sports.dialog

import android.app.Dialog
import android.os.Bundle
import android.view.View
import android.view.WindowManager
import androidx.fragment.app.Fragment
import androidx.fragment.app.FragmentActivity
import androidx.lifecycle.lifecycleScope
import com.lz.library.dialog.BaseDialogFragment
import com.lz.library.extension.countDown
import com.lz.sports.R
import com.lz.sports.databinding.DialogDelayedLoadingBinding
import kotlinx.coroutines.flow.collect
import kotlinx.coroutines.flow.onCompletion
import kotlinx.coroutines.launch

//延时加载弹窗
class DelayedLoadingDialog : BaseDialogFragment<DialogDelayedLoadingBinding>() {

    companion object {
        fun show(activity: FragmentActivity, time: Int = 2): DelayedLoadingDialog {
            val dialog = DelayedLoadingDialog().also {
                it.arguments = Bundle().apply { putInt("time", time) }
            }
            dialog.setFrom(true)
            dialog.show(activity.supportFragmentManager)
            return dialog
        }

        fun show(fragment: Fragment, time: Int = 2): DelayedLoadingDialog {
            val dialog = DelayedLoadingDialog().also {
                it.arguments = Bundle().apply { putInt("time", time) }
            }
            dialog.show(fragment.childFragmentManager)
            return dialog
        }
    }

    override fun getLayoutRes(): Int = R.layout.dialog_delayed_loading

    override fun initData(v: View, savedState: Bundle?) {
        val time = arguments!!.getInt("time")
        lifecycleScope.launch {
            countDown(time).onCompletion { dismiss() }.collect {}
        }
    }

    override fun onCreateDialog(savedInstanceState: Bundle?): Dialog = object : BaseDialog(requireContext(), outsideCancel = false) {
        override fun initParams(params: WindowManager.LayoutParams) {
            params.width = WindowManager.LayoutParams.WRAP_CONTENT
        }
    }
}